// service/integralShop/integralShop.js
import http from '../../utils/http'
import { formatTime, toast } from '../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeList: [
      {
        name: '自提点'
      },
      {
        name: '商家配送'
      }
    ],
    current: 0,
    show: false,
    userIntegralInfo: {},
    schedule: 0,
    cateList: [],
    currentCate: 0,
    page: 1,
    goodsList: [],
    status: 'loadmore', //loadmore加载更多 loading加载中 nomore没有更多了
    detail: {},
    goodsCount: 1,
    siteInfo: {}, // 自提点地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.getUserIntegralInfo()
    await this.getCate()
    this.getGoodsList()
  },
  // 获取用户积分信息
  getUserIntegralInfo() {
    http.post('points/userPoints', '', true).then(res => {
      if (res.code === 1) {
        this.setData({
          userIntegralInfo: res.data,
        })
        this.getSchedule(res.data)
      }
    })
  },
  getSchedule(info) {
    const schedule = Math.min(Math.max((info.used_points / info.total_points) * 100, 0), 100)
    this.setData({
      schedule
    })
  },
  // 商品分类
  async getCate() {
    return new Promise(resolve => {
      http.post('points/categories', '', true).then(res => {
        if (res.code === 1) {
          this.setData({
            cateList: res.data
          })
          resolve(res.data)
        }
      })
    })
  },
  resetLoadGoods() {
    this.setData({
      page: 1,
      status: 'loadmore',
      goodsList: [],
    })
    this.getGoodsList()
  },
  // 获取热门商品
  getGoodsList() {
    const { page, goodsList, status, cateList, currentCate } = this.data
    if (status === 'nomore') return;
    this.setData({
      status: 'loading'
    })
    const data = {
      category_id: cateList[currentCate].id || '',
      page: page,
      limit: 10,
    }
    http.post('points/goodsList', data, true).then(res => {
      if (res.code === 1) {
        res.data.data.forEach(item => {
          item.integralText = item.is_points_price ? `${item.points} + ￥${item.price}` : item.points
        })
        let list = goodsList
        list.push(...res.data.data)
        let newStatus = res.data.last_page > page ? 'loadmore' : 'nomore'
        this.setData({
          goodsList: list,
          status: newStatus
        })
      }
    })
  },
  changeCate(e) {
    const { index } = e.currentTarget.dataset
    if (index === this.data.currentCate) return
    this.setData({
      currentCate: index
    })
    this.resetLoadGoods()
  },
  getDetail(id) {
    const data = {
      id
    }
    return new Promise((resolve) => {
      http.post('points/goodsDetail', data, true).then(res => {
        if (res.code === 1) {
          resolve(res.data)
        }
      })
    })
  },
  change(e) {
    const { index } = e.currentTarget.dataset
    if (index === this.data.current) return
    this.setData({
      current: index
    })
  },
  async exchange(e) {
    const { id } = e.currentTarget.dataset
    let detail = await this.getDetail(id)
    detail.createTimeText = formatTime(detail.createtime)
    detail.integralText = detail.is_points_price ? `${detail.points} + ￥${detail.price}` : detail.points

    this.setData({
      show: true,
      detail,
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  increase() {
    const { goodsCount, detail } = this.data
    if (detail.stock === goodsCount) return toast('已经是最大库存了')
    this.setData({
      goodsCount: goodsCount + 1
    })
  },
  decrease() {
    const { goodsCount } = this.data
    if (goodsCount <= 1) return
    this.setData({
      goodsCount: goodsCount - 1
    })
  },
  goShop() {
    wx.navigateTo({
      url: '/service/outlet/outlet',
      events: {
        acceptAddress: (res) => {
          this.setData({
            siteInfo: res
          })
        }
      }
    })
  },
  payment() {
    // 检查是否选择了自提点
    if (!this.data.siteInfo || !this.data.siteInfo.id) {
      wx.showToast({
        title: '请选择自提点',
        icon: 'none'
      });
      return;
    }
    
    // 检查商品信息和数量
    if (!this.data.detail || !this.data.detail.id || this.data.goodsCount <= 0) {
      wx.showToast({
        title: '请选择有效商品和数量',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '提交中...',
      mask: true
    });
    
    // 准备请求参数
    const data = {
      goods_id: this.data.detail.id,
      quantity: this.data.goodsCount,
      store_id: this.data.siteInfo.id
    };
    
    // 调用创建订单接口
    http.post('points/createOrder', data, true).then(res => {
      wx.hideLoading();
      if (res.code === 1) {
        // 订单创建成功
        wx.showToast({
          title: '兑换成功',
          icon: 'success'
        });
        
        // 关闭弹窗
        this.setData({
          show: false
        });
        
        // 可以跳转到订单详情页或成功页
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/order/list/list?type=3' // 假设这是积分订单列表页
          });
        }, 1500);
      } else {
        console.log(res)
        // 订单创建失败
        wx.showToast({
          title: res.msg || '兑换失败，请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none'
      });
      console.error('创建订单失败:', err);
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { page, status } = this.data
    if (status === 'loading') return
    const newPage = page + 1
    this.setData({
      page: newPage,
    })
    this.getGoodsList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})